package com.xpec.c4.service.consistenthash;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 一致性hash ，用於多個相同module的分配
 * @author TW15012
 */
public class ConsistentHash <T>
{
	private  MessageDigest md5 = null;
	private  int numberOfReplicas;
	private  SortedMap<Long, T> circle = new TreeMap<Long, T>();
	private  Set<T> orgNodes;
	
	public ConsistentHash(int replicas , Set<T> nodes)
	{
		this.numberOfReplicas = replicas;
		for (T node : nodes) 
		{
            add(node);
        }
		
		orgNodes = nodes;
	}
	
	
	private   long hash(String key)
	{
		 if (md5 == null) {
	            try {
	                md5 = MessageDigest.getInstance("MD5");
	            } catch (NoSuchAlgorithmException e) {
	                throw new IllegalStateException("no md5 algorythm found");
	            }
	        }

		 	byte[] bKey = null;
	        synchronized (md5) {
		        md5.reset();
		        md5.update(key.getBytes());
		        bKey = md5.digest();
			}

	        long res = ((long) (bKey[3] & 0xFF) << 24) | ((long) (bKey[2] & 0xFF) << 16) | ((long) (bKey[1] & 0xFF) << 8)
	                | (long) (bKey[0] & 0xFF);
	        return res & 0xffffffffL;
	}
	
	
	public void add(T node)
	{
		for (int i = 0; i < numberOfReplicas; i++) {
            circle.put(hash(node.toString() + i), node); 
        }
	}
	
	
	public void remove(T node)
	{
		 for (int i = 0; i < numberOfReplicas; i++) {
	            circle.remove(hash(node.toString() + i));
	       }
	}
	
	public T get(String key)
	{
		if (circle.isEmpty()) {
            return null;
        }
		
		long hash = hash((String) key);
		
		
		 if (!circle.containsKey(hash)) {
	            SortedMap<Long, T> tailMap = circle.tailMap(hash);
	            hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
	        }
	        return circle.get(hash);
	}
	
	public T getFirstValue(){
		T[] elements = (T[]) circle.values().toArray();	
		return elements[0];
	}
	
	private int size()
	{
		return circle.size();
	}


	/**
	 * @return the orgNodes
	 */
	public Set<T> getOrgNodes() {
		return orgNodes;
	}
}
